//1. 引入express
const express = require('express');

//2. 创建应用对象
const app = express();

//3. 创建路由规则
// request 是对请求报文的封装
// response 是对响应报文的封装
app.get('/server', (request, response) => {
  //设置响应头  设置允许跨域
  // response.setHeader('Access-Control-Allow-Origin', '*');
  //设置响应体
  // response.send('HELLO AJAX - GET');
});

//4. 监听端口启动服务
app.listen(8888, () => {
  console.log("服务已经启动, 8888 端口监听中....");
});

//静态资源托管
app.use(express.static('./8-自我练习'))

//重定向
app.all('/', (req, res) => {
  res.redirect('/1get.html');
})

//路由设计
//1.get方法
app.get('/ajaxget', (req, res) => {
  //返回数据
  res.send('ajaxget ok!')
})



app.get('/chuancan', (req, res) => {

  //前台传参
  console.log(req.query)

  //返回数据
  res.send({
    "code": 1,
    "msg": "查找成功！",
    "data": {
      "usermane": req.query.username,
      "pwd": req.query.pwd
    }
  })
})

app.get('/restful/:username', (req, res) => {

  // var canshu = req.query;

  //RESTful style
  var canshu = req.params;
  console.log(canshu)

  //返回数据
  res.send({
    "code": 1,
    "msg": "查找成功！",
    "data": {
      "usermane": canshu.username
    }
  })
})



//post

app.use(express.urlencoded({
  extended: false
}))

app.post('/server', (request, response) => {
  //设置响应头  设置允许跨域
  // response.setHeader('Access-Control-Allow-Origin', '*');
  //响应头
  // response.setHeader('Access-Control-Allow-Headers', '*');
  //设置响应体

  var data = request.body;
  console.log(data)

  response.send(data);
});